package logic

import (
	"context"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"short-video-dev/cache"
	"short-video-dev/mysql"
	"short-video-dev/pkg"

	"short-video-dev/videorpc/internal/svc"
	"short-video-dev/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PwdForgetLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPwdForgetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PwdForgetLogic {
	return &PwdForgetLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 密码重置
func (l *PwdForgetLogic) PwdForget(in *videorpc.PwdForgetRequest) (*videorpc.PwdForgetResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.UserInfo
	err := user.FindUserByMobile(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, errors.New("用户不存在,请先注册")
	}

	smsKey := fmt.Sprintf("sms_%v", in.Mobile)
	sms, _ := cache.Rdb.Get(l.ctx, smsKey).Result()

	if in.SmsCode == "" {
		return nil, errors.New("请输入验证码")
	}
	if sms == "" {
		return nil, errors.New("验证码已过期，请重新获取")
	}
	if sms != in.SmsCode {
		return nil, errors.New("验证码错误,请重新输入")
	}

	if in.Password != in.NewPassword {
		return nil, errors.New("两次密码输入不一致")
	}

	var updatePwd = mysql.UserInfo{
		Model: gorm.Model{ID: user.ID},
		Pwd:   pkg.Md5(in.NewPassword),
	}

	err = updatePwd.UserUpdate(mysql.DB)
	if err != nil {
		return nil, errors.New("密码重置失败")
	}

	return &videorpc.PwdForgetResponse{}, nil
}
